var urlRoot = '../model/';

var id;
var inputFrame;

$(function() {

	inputFrame = new FrameItem("frameHolder", frameOk);

	id = getQueryString("id");
	refreshInfo();
	refreshModel();
	refreshLogNum();
});

var paramNum = 0;
var paramData = {}

var nowApi = undefined;
var nowModel = undefined;
var models = []
var testReturn = undefined;

function frameOk(popFrame) {

	var param = {}
	param.id = nowApi.id;
	param.key = popFrame.getInput();

	jQuery.ajax({
		type: 'POST',
		contentType: 'application/json',
		url: urlRoot + "setapikey",
		data: JSON.stringify(param),
		dataType: 'json',
		async: false,
		success: function(data) {
			if (checkApiErrorInfo(data, "提交API信息失败", null, popFrame.infoId)) {
				nowApi.url = data.url;
				nowApi.apikey = data.apikey;
				$("#apiurl").html(nowApi.url);
				popFrame.hide();
				log("修改API KEY成功");
			}
		},
		error: function(e) {
			showAjaxError(e);
		}
	});
}

function editKey() {
	inputFrame.show(true, "编辑API KEY", "输入新的Api Key", nowApi.apikey);
}

function promptChange(type) {
	var str;

	if (type == 2)
		str = $("#input_prompt_user").val();
	else
		str = $("#input_prompt_sys").val();

	var len = str.length;

	var id = "#prompt_len" + type;
	$(id).html(len);
}

function refreshModel() {
	jQuery.ajax({
		type: 'GET',
		contentType: 'application/json',
		url: urlRoot + 'models',
		dataType: 'json',
		async: false,
		success: function(data) {
			if (checkApiErrorInfo(data, "获取模型信息出错")) {
				models = data.models;

				var selStr = "<option value=0>---- 未选择模型 ----</option>";
				var mTitle = "NoModel";

				for (var i = 0; i < models.length; i++) {
					var md = models[i];

					if (md.id == nowModel)
						mTitle = md.title;

					selStr += "<option id='modelsel" + md.id + "' value=" + md.id + ">";
					selStr += md.title + " [" + md.model + "] [" + md.url + "]";
					selStr += "</option>";
				}

				$("#inputModel").html(selStr);

				if (nowModel) {
					$('#modelsel' + nowModel).attr('selected', true);
				}

				$("#itemTitle").html("编辑模API信息: [" + nowApi.id + "] [" + mTitle + "] " + nowApi.title);
			}

			if (data.info)
				log(data.info);
		},
		error: function(e) {
			log("返回结果出错： " + JSON.stringify(e));
		}
	});
}

function refreshInfo() {

	if (id < 0) {
		$("#itemTitle").html("新增API信息");
		return;
	}

	jQuery.ajax({
		type: 'GET',
		contentType: 'application/json',
		url: urlRoot + 'getapi?id=' + id,
		dataType: 'json',
		async: false,
		success: function(data) {
			if (checkApiErrorInfo(data, "获取API信息出错")) {
				nowApi = data.data;

				$("#input_title").val(nowApi.title);
				nowModel = nowApi.modelid;
				$("#input_prompt_user").val(nowApi.prompt);
				$("#input_prompt_sys").val(nowApi.system);

				var uh = nowApi.promptUh;
				var sh = nowApi.promptSh;

				if (uh > 10)
					$("#input_prompt_user").height(uh);
				if (sh > 10)
					$("#input_prompt_sys").height(sh);

				promptChange(1);
				promptChange(2);
				$("#apiurl").html(nowApi.url);
				$("#itemTitle").html("编辑模API信息: [" + id + "] [NoModel] " + nowApi.title);

				paramNum = 0;
				var params = nowApi.paramdata;
				var paramStr = "";

				for (var i = 0; i < params.length; i++) {
					var p = params[i];
					paramStr += makeParam(p);
				}
				paramStr += makeParam();

				$("#paramHolder").html(paramStr);
			}
			else {
				if (data.stay < 0) {
					toPage('./index.html');
				}
			}

			if (data.info)
				log(data.info);
		},
		error: function(e) {
			log("返回结果出错： " + JSON.stringify(e));
		}
	});
}

function refreshLogNum() {

	jQuery.ajax({
		type: 'GET',
		contentType: 'application/json',
		url: urlRoot + 'getapilognum?api=' + id,
		dataType: 'json',
		async: false,
		success: function(data) {
			if (checkApiErrorInfo(data, "获取API信息出错")) {
				var num = data.num;

				if (!num || num < 0)
					num = 0;

				$("#save_num").html("现有: " + num);

			}
		},
		error: function(e) {
			log("返回结果出错： " + JSON.stringify(e));
		}
	});
}

function makeParam(data) {

	var key = "";
	var value = "";
	var title = "";
	var def = "";

	if (data) {
		key = data.k;
		value = data.v;
		title = data.t;
		def = data.d;
	}

	var num = paramNum;
	paramNum++;
	paramData[num] = num;

	if (value == undefined)
		value = "";
	if (def == undefined)
		def = "";

	var str = "<tr id='param" + num + "'>";
	str += "<td style='text-align: left; vertical-align: middle'><input style='text-align: left; width: 100%; height: 32px' id='param_key";
	str += num + "' value='" + key + "'></td >";
	str += "<td style='text-align: left; vertical-align: middle'><input style='text-align: left; width: 100%; height: 32px' id='param_title";
	str += num + "' value='" + title + "'></td >";
	str += "<td  style='text-align: left; vertical-align: middle'><input style='text-align: left; width: 100%; height: 32px' id='param_def";
	str += num + "' value='" + def + "'></td >";
	str += "<td  style='text-align: left; vertical-align: middle'><input style='text-align: left; width: 100%; height: 32px' id='param_value";
	str += num + "' value='" + value + "'></td >";
	str += "<td  style='text-align: center; width: 48px'><span class='btn-del btn btn32 ripple' onclick='delParam(" + num + ")'></span></td >";
	str += "</tr>";

	return str;
}

function getCurrentParamData() {
	var result = [];

	for (let num in paramData) {
		var v = paramData[num];
		if (v < 0)
			continue;

		var keyId = "param_key" + num;
		var titleId = "param_title" + num;
		var valueId = "param_value" + num;
		var defId = "param_def" + num;

		var item = {}

		item.k = $("#" + keyId).val();
		item.v = $("#" + valueId).val();
		item.d = $("#" + defId).val();
		item.t = $("#" + titleId).val();

		result.push(item);
	}

	return result;
}

function delParam(num) {
	paramData[num] = -1;

	var id = "param" + num;
	$("#" + id).remove();
}

function commit() {

	var param = {}

	var method;
	if (id < 0) {
		method = "createapi";
	}
	else {
		method = "updateapi";
		param.id = id;
	}

	param.title = $("#input_title").val();
	param.prompt = $("#input_prompt_user").val();
	param.system = $("#input_prompt_sys").val();
	param.modelid = $("#inputModel option:selected").val();

	param.paramdata = getCurrentParamData();

	param.promptUh = $("#input_prompt_user").height();
	param.promptSh = $("#input_prompt_sys").height();

	jQuery.ajax({
		type: 'POST',
		contentType: 'application/json',
		url: urlRoot + method,
		data: JSON.stringify(param),
		dataType: 'json',
		async: false,
		success: function(data) {
			if (checkApiErrorInfo(data, "提交API信息失败")) {
				refreshInfo();
				refreshModel();
				log("保存完成");
			}
		},
		error: function(e) {
			showAjaxError(e);
		}
	});
}

function addParam() {
	var paramStr = makeParam("", "", "");
	$("#paramHolder").append(paramStr);
}

function promptTest() {
	var param = {}
	param.title = $("#input_title").val();
	param.prompt = $("#input_prompt_user").val();
	param.system = $("#input_prompt_sys").val();

	param.paramdata = getCurrentParamData();

	jQuery.ajax({
		type: 'POST',
		contentType: 'application/json',
		url: urlRoot + 'promptTest',
		data: JSON.stringify(param),
		dataType: 'json',
		async: false,
		success: function(data) {
			if (checkApiErrorInfo(data, "提交API信息失败")) {
				$("#output_test").html(data.prompt);
				testReturn = undefined;
				$("#save_info").html("");
				log("");
			}
			else {
				$("#output_info").html("测试失败:" + data.errmsg);
			}
		},
		error: function(e) {
			showAjaxError(e);
		}
	});
}

function apiTest() {

	var param = {}
	param.title = $("#input_title").val();
	param.prompt = $("#input_prompt_user").val();
	param.system = $("#input_prompt_sys").val();
	param.modelid = $("#inputModel option:selected").val();
	if (debug)
		param.dolog = true;

	param.paramdata = getCurrentParamData();
	
	console.log(param);

	jQuery.ajax({
		type: 'POST',
		contentType: 'application/json',
		url: urlRoot + 'apiTest',
		data: JSON.stringify(param),
		dataType: 'json',
		async: false,
		success: function(data) {
			if (checkApiErrorInfo(data, "提交API信息失败")) {
				$("#output_test").html(data.response);
				$("#output_info").html(data.cost);

				testReturn = data;
				testReturn.api = nowApi.id;
				testReturn.saved = false;
				$("#save_info").html("");
				log("");
			}
			else {
				$("#output_info").html("测试失败:" + data.errmsg);
			}
		},
		error: function(e) {
			showAjaxError(e);
		}
	});
}

function saveResult() {

	if (!testReturn) {
		$("#save_info").html("无测试结果。");
		return;
	}

	if (testReturn.saved) {
		$("#save_info").html("数据已保存。");
		return;
	}

	jQuery.ajax({
		type: 'POST',
		contentType: 'application/json',
		url: urlRoot + 'saveTestLog',
		data: JSON.stringify(testReturn),
		dataType: 'json',
		async: false,
		success: function(data) {
			if (checkApiErrorInfo(data, "提交API信息失败")) {
				testReturn.saved = true;
				$("#save_info").html("保存完成:" + data.info);
				refreshLogNum();
			}
			else {
				$("#save_info").html("测试失败:" + data.errmsg);
			}
		},
		error: function(e) {
			showAjaxError(e);
		}
	});
}

function showHistory() {
	toPage("./history.html?id=" + id);
}